<!--
 * @Descripttion: 出库表单
 * @LastEditors: xzh
 * @LastEditTime: 2023-11-04 21:59:35
-->
<template>
  <el-form
    ref="formRef"
    class="el-form-card"
    :model="outBoundForm.formData"
    :rules="formRules"
    label-width="6rem"
    size="large"
    status-icon
  >
    <el-card>
      <template #header>
        <span>{{
          $t("page.equipSpareArr.outBoundManageArr.outBoundInfo")
        }}</span>
      </template>
      <el-col :span="12">
        <el-form-item :label="$t('page.equipSpareArr.outBoundManageArr.code')">
          <el-input
            v-model="outBoundForm.formData.code"
            disabled
            :placeholder="$t('common.systemAutoGenerate')"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item
          :label="$t('page.equipSpareArr.outBoundManageArr.name')"
          prop="name"
        >
          <el-input
            v-model="outBoundForm.formData.name"
            :placeholder="$t('common.enter')"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item
          :label="$t('page.equipSpareArr.outBoundManageArr.type')"
          prop="type"
        >
          <el-select
            v-model="outBoundForm.formData.type"
            :placeholder="$t('common.select')"
          >
            <el-option
              v-for="outBoundType in Object.keys(outBoundTypeEnum)"
              :key="outBoundType"
              :label="
                $t(
                  `page.equipSpareArr.outBoundManageArr.typeArr.${outBoundType}`
                )
              "
              :value="outBoundType"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item
          :label="$t('page.equipSpareArr.outBoundManageArr.stockOutDateTime')"
          prop="stockOutDateTime"
        >
          <el-date-picker
            v-model="outBoundForm.formData.stockOutDateTime"
            type="date"
            :placeholder="$t('common.selectDateTime')"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item
          :label="$t('page.equipSpareArr.outBoundManageArr.applicant')"
        >
          <!-- 输入框选择对象 -->
          <DileInputSelectItem
            v-model="outBoundForm.formData.applicant"
            :selectType="selectTypeEnum.people"
            :cacheLabel="outBoundForm.formData.extJson.applicantName"
            @itemSelected="handleApplicantSelected"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item
          :label="$t('page.equipSpareArr.outBoundManageArr.department')"
        >
          <el-input
            v-model="outBoundForm.formData.extJson.applicantDepartmentName"
            disabled
            :placeholder="$t('common.systemAutoBringOut')"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item
          :label="$t('page.systemManageArr.storeManageArr.name')"
          prop="warehouseId"
          :validate-status="
            !!outBoundForm.formData.warehouseId ? 'success' : ''
          "
        >
          <!-- 输入框选择对象 -->
          <DileInputSelectItem
            v-model="outBoundForm.formData.warehouseId"
            :expand-on-click-node="false"
            :selectType="selectTypeEnum.store"
            :cacheLabel="outBoundForm.formData.extJson.warehouseName"
            @itemSelected="handleStoreSelected"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item
          :label="$t('page.systemManageArr.storeManageArr.manager')"
        >
          <el-input
            v-model="outBoundForm.formData.extJson.warehouseManagerName"
            disabled
            :placeholder="$t('common.systemAutoBringOut')"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item
          :label="$t('page.equipSpareArr.outBoundManageArr.stockOutUser')"
        >
          <!-- 输入框选择对象 -->
          <DileInputSelectItem
            v-model="outBoundForm.formData.stockOutUserId"
            :selectType="selectTypeEnum.people"
            :cacheLabel="outBoundForm.formData.extJson.stockOutUserName"
          />
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item :label="$t('common.remark')">
          <el-input
            v-model="outBoundForm.formData.remark"
            :rows="5"
            type="textarea"
          />
        </el-form-item>
      </el-col>
    </el-card>
    <!-- 备件明细 -->
    <el-card>
      <template #header>
        <span>{{ $t("page.equipRepairArr.spareDetails") }}</span>
      </template>
      <!-- 关联备件明细 -->
      <RelSpareTable ref="relSpareTableRef">
        <template #extClounm>
          <vxe-column width="200">
            <template #header>
              <span :style="{ color: 'red' }">*</span>
              <span>{{
                $t("page.equipSpareArr.outBoundManageArr.thisStockOutNumber")
              }}</span>
            </template>
            <template #default="{ row }">
              <el-input-number
                v-model="row.stockOutNumber"
                controls-position="right"
                :min="0"
                size="default"
              />
            </template>
          </vxe-column>
        </template>
      </RelSpareTable>
      <div class="div-sumStockOutNum">
        <span
          >{{
            $t("page.equipSpareArr.outBoundManageArr.sumStockOutNum")
          }}:</span
        >
        <span :style="{ color: 'red' }"> {{ sumStockOutNum }}</span>
      </div>
    </el-card>
  </el-form>
</template>

<script setup lang="ts">
import { ref, reactive, toRefs, computed, nextTick } from "vue";
import type { object_Inf } from "@/utils/typings/index.type";
import { useI18n } from "vue-i18n";
import { ElNotification } from "element-plus";
import { selectTypeEnum } from "@/components/dile-selectItem/index.type";
import { outBoundTypeEnum } from "@/utils/typings/equipManage/equipSpare/index.type";
import DileInputSelectItem from "@/components/dile-selectItem/selectItem-input/index.vue";
import RelSpareTable from "@/views/equipManage/equipSpare/spareLedger/spareLedger-relTable/index.vue";
import Dile_APi from "@/api";

const emit = defineEmits(["refresh"]);

let { t } = useI18n();

/**
 * @Author: xzh
 * @Descripttion: 备件明细表格实例
 * @Param:
 */
let relSpareTableRef = ref<any>(null);

/**
 * @Author: xzh
 * @Descripttion: 表单默认数据
 * @Param:
 */
let defaultData = () => ({
  id: 0,
  name: "", //出库名称
  code: "", //出库编码
  type: "", //出库类型
  stockOutDateTime: "", //出库日期
  applicant: null, //出库申请人
  warehouseId: null, //仓库
  stockOutUserId: null, //出库人员
  remark: "", //备注
  extJson: {
    applicantName: "", //出库申请人名称
    applicantDepartmentName: "", //所在部门
    warehouseName: "", //仓库名称
    warehouseManagerName: "", //仓库管理员名称
    stockOutUserName: "", //出库人员名称
  },
});
/**
 * @Author: xzh
 * @Descripttion: 出库表单参数
 * @Param:
 */
let outBoundForm = reactive<object_Inf>({
  //表单数据
  formData: defaultData(),
});

/**
 * @Author: xzh
 * @Descripttion: 表单实例
 * @Param:
 */
let formRef = ref<any>(null);

/**
 * @Author: xzh
 * @Descripttion:表单验证规则
 * @Param:
 * @param {*} computed
 */
let formRules = computed((): any => {
  return reactive({
    name: [
      {
        required: true,
        message:
          t("common.enter") +
          t("page.organizeManageArr.departmentArr.departName"),
        trigger: "change",
      },
    ],
    type: [
      {
        required: true,
        message:
          t("common.enter") + t("page.equipSpareArr.outBoundManageArr.type"),
        trigger: "change",
      },
    ],
    stockOutDateTime: [
      {
        required: true,
        message:
          t("common.select") +
          t("page.equipSpareArr.outBoundManageArr.stockOutDateTime"),
        trigger: "change",
      },
    ],
    warehouseId: [
      {
        required: true,
        message:
          t("common.select") + t("page.systemManageArr.storeManageArr.name"),
        trigger: "change",
      },
    ],
  });
});

/**
 * @Author: xzh
 * @Descripttion: 计算总出库数量
 * @Param:
 * @param {*} computed
 */
let sumStockOutNum = computed(() => {
  let relData: object_Inf = (relSpareTableRef.value?.getTableData() || [])
    ?.map((x: object_Inf) => x.stockOutNumber)
    .filter((x: any) => !!x);

  return relData.length > 0
    ? relData.reduce((x: any, y: any) => (Number(x) || 0) + (Number(y) || 0))
    : 0;
});
/**
 * @Author: xzh
 * @Descripttion: 加载表单数据
 * @Param:
 */
let initFormData = async (id: number) => {
  let { model, dataList, relations }: object_Inf = !!id
    ? await Dile_APi.getEquipOutBoundInfo(id)
    : { model: defaultData() };
  Object.assign(outBoundForm.formData, model);
  //格式化关联备件信息
  if (dataList?.length > 0) {
    let relSpareArr = dataList
      .map((spare: object_Inf) => {
        let { id, stockOutNumber } = relations?.find(
          (x: object_Inf) => x.sparePartId == spare.id
        );
        return !!id
          ? {
              ...spare,
              stockOutNumber,
              relId: id,
            }
          : {};
      })
      .filter((x: object_Inf) => !!x.id);
    //加载关联备件表格
    relSpareTableRef.value.initTableData(relSpareArr);
  }
};

/**
 * @Author: xzh
 * @Descripttion: 仓库选择
 * @Param:
 * @param {*} dataArr
 */
let handleStoreSelected = (dataArr: Array<object_Inf>) => {
  let { name, id, extJson }: object_Inf = dataArr.find(() => true) || {},
    { managerName } = extJson || {};

  Object.assign(outBoundForm.formData, {
    warehouseId: id,
    extJson: {
      ...outBoundForm.formData.extJson,
      warehouseName: name,
      warehouseManagerName: managerName,
    },
  });
};
/**
 * @Author: xzh
 * @Descripttion: 出库申请人选择
 * @Param:
 * @param {*} dataArr
 */
let handleApplicantSelected = (dataArr: Array<object_Inf>) => {
  let { name, id, orgName, extJson }: object_Inf =
    dataArr.find(() => true) || {};

  Object.assign(outBoundForm.formData, {
    applicant: id,
    extJson: {
      ...outBoundForm.formData.extJson,
      applicantName: name,
      applicantDepartmentName: orgName,
    },
  });
};
/**
 * @Author: xzh
 * @Descripttion: 保存事件
 * @Param:
 */
let hanldeSaveForm = async (isSave: boolean = true) => {
  let { formData } = outBoundForm,
    valid = await formRef.value.validate();
  //表单验证&&关联备件验证
  if (!valid || !verifyRelSpare()) {
    return false;
  }
  let { id } = formData,
    relData: object_Inf = relSpareTableRef.value.getRelData();
  //格式化关联备件信息
  Object.keys(relData)
    .filter((x) => x != "deleteRelations")
    .forEach(
      (relkey) =>
        (relData[relkey] = relData[relkey].map((x: object_Inf) => {
          let { id: spareId, stockOutNumber, relId } = x;
          return {
            id: relId,
            sparePartId: spareId,
            stockOutId: id,
            stockOutNumber,
          };
        }))
    );
  let data = {
    model: formData,
    ...relData,
  };
  //判断不默认保存
  if (!isSave) {
    return data;
  }
  await Dile_APi.saveEquipOutBound(data);
  //触发刷新回调
  emit("refresh");
  //提示成功
  ElNotification({
    message: t("common.message.OperationSuccess"),
    type: "success",
  });
};
/**
 * @Author: xzh
 * @Descripttion: 验证关联备件
 * @Param:
 */
let verifyRelSpare = () => {
  let relSpareData: object_Inf = relSpareTableRef.value.getTableData();
  //获取出库数量为空数组
  let emptyOutNumArr = relSpareData.filter(
    (x: object_Inf) => !!x.id && !x.stockOutNumber
  );
  if (emptyOutNumArr.length > 0) {
    ElNotification({
      message: `[${emptyOutNumArr
        .map((x: object_Inf) => x.name)
        .join(",")}]:${t("common.enter")}${t(
        "page.equipSpareArr.outBoundManageArr.thisStockOutNumber"
      )}`,
      type: "warning",
    });
    return false;
  }
  return true;
};

defineExpose({
  initFormData,
  hanldeSaveForm,
});
</script>
<style lang="scss" scoped>
.div-sumStockOutNum {
  display: flex;
  justify-content: flex-end;
  width: 100%;
  padding: 0 5%;
  gap: 0.5rem;
}
</style>
